<?php


declare(strict_types=1);

namespace app\seller\controller\admin;

use app\seller\model\Brand as BrandModel;
use sheep\controller\Backend;
use think\facade\Db;
use think\Request;
use think\Response;
use app\shop\service\pay\PayRefund;
use Yansongda\Pay\Pay as YansongdaPay;
use app\shop\model\Pay as PayModel;
use app\shop\service\pay\PayOper;
use app\shop\library\pay\PayService;
use app\shop\model\PayConfig as PayConfigModel;
use Yansongda\Pay\Provider\Alipay;
use Alipay\EasySDK\Kernel\Factory;
use Alipay\EasySDK\Kernel\Config;
use Alipay\EasySDK\Payment\Common\Models\AlipayTradeCreateResponse;

//支付
class Pay extends Backend
{


//    protected $config = [
//        'app_id' => '2021004138624402',
//        'notify_url' => 'http://yansongda.cn/notify.php',
//        'return_url' => 'http://yansongda.cn/return.php',
//        'ali_public_key' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuWJKrQ6SWvS6niI+4vEVZiYfjkCfLQfoFI2nCp9ZLDS42QtiL4Ccyx8scgc3nhVwmVRte8f57TFvGhvJD0upT4O5O/lRxmTjechXAorirVdAODpOu0mFfQV9y/T9o9hHnU+VmO5spoVb3umqpq6D/Pt8p25Yk852/w01VTIczrXC4QlrbOEe3sr1E9auoC7rgYjjCO6lZUIDjX/oBmNXZxhRDrYx4Yf5X7y8FRBFvygIE2FgxV4Yw+SL3QAa2m5MLcbusJpxOml9YVQfP8iSurx41PvvXUMo49JG3BDVernaCYXQCoUJv9fJwbnfZd7J5YByC+5KM4sblJTq7bXZWQIDAQAB',
//        // 加密方式： **RSA2**
//        'private_key' => 'MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCa',
//        'log' => [ // optional
//            'file' => './logs/alipay.log',
//            'level' => 'info', // 建议生产环境等级调整为 info，开发环境为 debug
//            'type' => 'single', // optional, 可选 daily.
//            'max_file' => 30, // optional, 当 type 为 daily 时有效，默认 30 天
//        ],
//        'http' => [ // optional
//            'timeout' => 5.0,
//            'connect_timeout' => 5.0,
//            // 更多配置项请参考 [Guzzle](https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html)
//        ],
//        'mode' => 'dev', // optional,设置此参数，将进入沙箱模式
//    ];


    protected $model = null;

    protected function initialize()
    {
        $this->model = new BrandModel;
        // 获取支付宝 SDK 配置
        $alipayConfig = config('aliyun');

        // 创建一个 Config 对象
        $config = new Config();
        $config->protocol = 'https';
        $config->gatewayHost = $alipayConfig['gateway_url'];
        $config->signType = $alipayConfig['sign_type'];
        $config->appId = $alipayConfig['app_id'];
        $config->merchantPrivateKey = $alipayConfig['merchant_private_key']; // 商户私钥配置
        $config->alipayPublicKey = $alipayConfig['alipay_public_key']; // 支付宝公钥配置
        $config->notifyUrl = $alipayConfig['notify_url']; // 回调地址
        $config->charset = 'UTF-8';
        $config->format = 'json';

        // 如果使用证书模式，需要配置证书路径
        if (isset($alipayConfig['merchant_cert_path'])) {
            $config->merchantCertPath = $alipayConfig['merchant_cert_path']; // 商户证书路径
        }
        if (isset($alipayConfig['alipay_cert_path'])) {
            $config->alipayCertPath = $alipayConfig['alipay_cert_path']; // 支付宝公钥证书路径
        }
        if (isset($alipayConfig['alipay_root_cert_path'])) {
            $config->alipayRootCertPath = $alipayConfig['alipay_root_cert_path']; // 支付宝根证书路径
        }

        // 设置配置
        Factory::setOptions($config);
    }


    /**
     * 网页支付
     */
    public function prepay(Request $request)
    {
//        $images['zfb'] = 'https://liuliangbenben.oss-cn-hangzhou.aliyuncs.com/storage/default/20240803/0b32cd353b866a2ddf6c6c8568e7f3e7.png';
//        $images['wx'] = 'https://liuliangbenben.oss-cn-hangzhou.aliyuncs.com/storage/default/20240803/a83341c096fb5b45004e050f3edc41a8.png';
//
//
//        return success('保存成功', $images);
//        return $images;
        //try {
            $result = Factory::payment()->faceToFace()->preCreate(
                'test subject - 测试', // 商品名称
                time(), // 商户订单号
                1.00   // 订单金额，单位元，精确到小数点后两位
            );

            if ($result->code === '10000') {
                // 返回二维码支付链接
                return json(['qr_code' => $result->qr_code]);
            } else {
                return json(['error' => $result->msg]);
            }
//        } catch (\Exception $e) {
//            return json(['error' => $e->getMessage()]);
//        }
//        $order = [
//            'out_trade_no' => time(),
//            'total_amount' => '1',
//            'subject' => 'test subject - 测试',
//            '_config' => 'alipay'
//        ];
//        $alipay = YansongdaPay::alipay(config('pay'))->scan($order);
        //$wechat = YansongdaPay::Wechat(config('pay.wechat'))->scan($order);
//        dd($alipay);
//        return $alipay->qr_code();// laravel 框架中请直接 `return $alipay`
        //$Factory = $this->config();
        // 创建订单并发起支付
//        try {
//            $response = Factory::payment()->common()->create(
//                '测试订单', // 商品标题
//                time(), // 订单号
//                '100.00', // 金额
//                ''
//            );
//            dd($response);
//            if ($response->code == 10000) {
//                // 支付成功，返回支付二维码链接
//                echo "支付二维码链接：" . $response->qrCode;
//            } else {
//                // 支付失败
//                echo "支付失败：" . $response->msg;
//            }
//        } catch (Exception $e) {
//            echo "错误：" . $e->getMessage();
//        }

    }

    public function config()
    {
        $alipay_config = config('pay.alipay');
        // 初始化 SDK
        $config = new Config();
        $config->protocol = 'https'; // 协议
        $config->gatewayHost = 'openapi.alipay.com'; // 支付宝网关
        $config->signType = 'RSA2'; // 签名方式

        // 应用信息
        $config->appId = $alipay_config['app_id'];
        $config->merchantPrivateKey = $alipay_config['app_secret_cert'];

        // 支付宝公钥
        $config->alipayPublicKey = '-----BEGIN CERTIFICATE-----
MIIDsjCCApqgAwIBAgIQICQDKXkRrdGTmsghINSq/DANBgkqhkiG9w0BAQsFADCBgjELMAkGA1UE
BhMCQ04xFjAUBgNVBAoMDUFudCBGaW5hbmNpYWwxIDAeBgNVBAsMF0NlcnRpZmljYXRpb24gQXV0
aG9yaXR5MTkwNwYDVQQDDDBBbnQgRmluYW5jaWFsIENlcnRpZmljYXRpb24gQXV0aG9yaXR5IENs
YXNzIDIgUjEwHhcNMjQwMzI5MDk0OTUxWhcNMjkwMzI4MDk0OTUxWjCBkjELMAkGA1UEBhMCQ04x
LTArBgNVBAoMJOadreW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0mw
7xdySzmGQku4GTyqutIGPQwKxSj9iSFw1FCZqr4VP4tyXzMUgc52SzagA6i7AyLedd3tbS6lnR5B
L+W9Kx9hwT8L7WANAxQzv/jGldeuSLN8bsTxlOYlsdjmIGu/C9OWblPYGpjQQIRyvs4Cc/mNhrh+
14EQgwuemIIFDLOgcD+iISoN8CqegelNcJndFw1PDN6LkVoiHz9p7jzsge8RKay/QW6C03KNDpWZ
EUCgCUdfHfo8xKeR+LL1cfn24HKJmZt8L/aeRZwZ1jwePXFRVtiXELvgJuM/tJDIFj2KD337iV64
fWcKQ/ydDVGqfDZAdcU4hQdsrPWENwPTQPfVPq2NNLMyIH9+WKx9Ed6/WzeZmIy5ZWpX1TtTolo6
OJXQFeItMAjHxW/ZSZTok5IS3FuRhExturaInnzjYpx50a6kS34c5+c8hYq7sAtZ/CNLZmBnBCFD
aMQqT8xFZJ5uolUaSeXxg7JFY1QsYp5RKvj4SjFwCGKJ2+hPPe9UyyltxOidNtxjaknOCeBHytOr
-----END CERTIFICATE-----';

        // 回调地址
        $config->notifyUrl = $alipay_config['notify_url'];
        $config->returnUrl = $alipay_config['return_url'];

        // 初始化 SDK 工厂
        return Factory::setOptions($config);
    }
}
